package com.cookies.servlets;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class GetCookiesServlet extends HttpServlet {

	private static final long serialVersionUID = -8344039162530020425L;

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();
		out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
		out.println("<HTML>");
		out.println("  <HEAD><TITLE>getCookies</TITLE></HEAD>");
		out.println("  <BODY>");
		out.println("从Cookie读取的赏赐登录日期与用户名：");
		Cookie[] cookies=request.getCookies();
		Cookie cookie=null;
		if(cookies!=null)
		{
			for(int i=0;i<cookies.length;i++)
			{
				cookie=cookies[i];
				if(cookie.getName().equals("username")){
					out.println("用户名："+cookie.getValue()+"<br>");
				}
				if(cookie.getName().equals("lastVisited")){
					out.println("上次访问的日期："+cookie.getValue()+"<br>");
				}
			}
		}
		out.println("  </BODY>");
		out.println("</HTML>");
		out.flush();
		out.close();
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doGet(request, response);
	}

}
